<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="addDialogVisible = true">添加用户</el-button></el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }}渲染当前一行数据的全部内容 -->
            <el-switch v-model="scope.row.mg_status" @change="userstatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 按钮页面 -->

          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="eidtDiglog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserbyId(scope.row.id, scope.row.username)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[2, 4, 8, 15]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>

    <!-- 用户表单区 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="adduserForm" :rules="adduserFormRules" ref="adduserFormRef" label-width="70px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adduserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="adduserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adduserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="adduserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改表单区 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="edituserForm" :rules="edituserFormRules" ref="edituserFormRef" label-width="70px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="edituserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="edituserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="edituserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserinfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->

    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRolesDiglogColsed">
      <div>
        <p>当前的用户:{{ userinfo.username }}</p>
        <p>当前的角色:{{ userinfo.role_name }}</p>
        <p>
          分配的新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      adduserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      adduserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3~10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在6~12个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { min: 5, max: 25, message: '长度在5~25个字符', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          // { min: 2, max: 11, message: '长度在11个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      editDialogVisible: false,
      edituserForm: {},
      edituserFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          // { min: 2, max: 11, message: '长度在11个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      setRoleDialogVisible: false,

      // 角色分配
      userinfo: '',
      rolesList: [],
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.userList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // total发生变化
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 页码发生变化
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userstatusChange(userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_status != userinfo.mg_status
        return this.$message.error('用户更新失败')
      }
      this.$message.success('更新成功')
    },

    addDialogClosed() {
      this.$refs.adduserFormRef.resetFields()
    },

    editDialogClosed() {
      this.$refs.edituserFormRef.resetFields()
    },

    addUser() {
      this.$refs.adduserFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post('users', this.adduserForm)
        if (res.meta.status !== 201) {
          return this.$message.error('用户添加失败')
        }
        this.$message.success(`用户${this.adduserForm.username}添加成功`)

        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        //重新调用=刷新列表
        this.getUserList()
      })
    },

    async eidtDiglog(id) {
      console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }

      this.edituserForm = res.data
      this.editDialogVisible = true
    },

    editUserinfo() {
      this.$refs.edituserFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put('users/' + this.edituserForm.id, {
          email: this.edituserForm.email,
          mobile: this.edituserForm.mobile
        })

        if (res.meta.status !== 200) {
          this.$message.error('更新用户数据失败')
        }

        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('更新数据成功')
      })
    },

    async removeUserbyId(id, username) {
      const confirmres = await this.$confirm('此操作将永久删除' + username + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 确定输出confirm,取消报错误,需要捕获异常
      if (confirmres !== 'confirm') {
        return this.$message.queryInfo('已取消该操作')
      }

      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('删除失败')
      }

      this.$message.success('已成功删除' + username)
      this.getUserList()
    },

    async setRole(userinfo) {
      this.userinfo = userinfo
      this.setRoleDialogVisible = true

      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色失败')
      }

      this.rolesList = res.data
    },

    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }

      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        this.$message.error('分配角色失败')
      }

      this.$message.success('更新角色成功')

      this.setRoleDialogVisible = false
      this.getUserList()
    },

    // 监听关闭事件
    setRolesDiglogColsed() {
      this.selectedRoleId = ''
      this.userinfo = {}
    }
  }
}
</script>

<style lang="less" scoped></style>
